using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace SsisUtilities.PacMan.Components
{
    public class DtprojHelper
    {
        public static List<FileInfo> GetPackageFiles(FileInfo projectFile)
        {
            XmlElement projectNode = GetProjectElement(projectFile);

            XmlNodeList packageNodes = projectNode.SelectNodes
                ("DTSPackages/DtsPackage/FullPath");

            DirectoryInfo projectFolder = projectFile.Directory;
            List<FileInfo> packageList = new List<FileInfo>();

            foreach (XmlNode packageNode in packageNodes)
            {
                XmlElement packageElement = (XmlElement)packageNode;
                string packagePath = packageElement.InnerXml;

                packageList.Add(new FileInfo(projectFolder.FullName + @"\" + packagePath));
            }

            return packageList;
        }

        public static List<PackageUtil> GetPackageUtils(FileInfo projectFile)
        {
            List<PackageUtil> packages = new List<PackageUtil>();
            foreach (FileInfo packageFile in GetPackageFiles(projectFile))
            {
                packages.Add(new PackageUtil(packageFile, projectFile.Name));
            }
            return packages;
        }


        public static void DeleteDataSources(FileInfo projectFile)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(projectFile.FullName);

            XmlElement projectNode = xmlDoc.DocumentElement;

            XmlNode dataSourcesNode = projectNode.SelectSingleNode
                ("DataSources");

            dataSourcesNode.RemoveAll();
            xmlDoc.Save(projectFile.FullName);
        }

        private static XmlElement GetProjectElement(FileInfo projectFile)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(projectFile.FullName);
            return xmlDoc.DocumentElement;
        }

    }
}
